import os
import json
from datetime import datetime

# 预设用户信息 {用户名: {'password': 'xxx', 'current_password': 'xxx'}}
users = {
}

# 可借阅的图书列表
available_books = []

# 借阅记录：{用户名: [{'book': '书名', 'returned': False, 'borrow_date': '日期'}, ...]}
borrow_records = {}

# 数据文件路径
DATA_FILE = 'Information.txt'

def load_data():
    """从Information.txt文件加载数据"""
    global users, borrow_records
    
    if os.path.exists(DATA_FILE):
        try:
            with open(DATA_FILE, 'r', encoding='utf-8') as f:
                data = json.load(f)
                
            # 加载用户数据（保留预设密码，但更新可能存在的修改）
            if 'users' in data:
                for username, user_info in data['users'].items():
                    if username in users:
                        # 如果用户存在，只更新密码（如果用户修改过）
                        if 'password' in user_info:
                            users[username]['password'] = user_info['password']
                    else:
                        # 如果是新用户，添加到系统中
                        users[username] = {'password': user_info.get('password', '')}
            
            # 加载借阅记录
            if 'borrow_records' in data:
                borrow_records = data['borrow_records']
            
            print("数据加载成功！")
        except Exception as e:
            print(f"数据加载失败，使用默认数据。错误信息: {e}")
    else:
        print("未找到数据文件，使用默认数据。")

def save_data():
    """将数据保存到Information.txt文件"""
    try:
        data = {
            'users': users,
            'borrow_records': borrow_records
        }
        
        with open(DATA_FILE, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
        
        print("数据保存成功！")
    except Exception as e:
        print(f"数据保存失败，错误信息: {e}")

def login():
    print("\n欢迎使用图书管理系统")
    while True:
        username = input("请输入用户名: ").strip()
        password = input("请输入密码: ").strip()

        if username in users and users[username]['password'] == password:
            print(f"\n登录成功！欢迎, {username}！")
            return username
        else:
            print("用户名或密码错误，请重新输入。\n")

def change_password(username):
    current_pwd = input("请输入当前密码: ").strip()
    if current_pwd != users[username]['password']:
        print("当前密码错误，修改失败。")
        return

    new_pwd = input("请输入新密码: ").strip()
    confirm_pwd = input("请再次输入新密码确认: ").strip()

    if new_pwd == confirm_pwd:
        users[username]['password'] = new_pwd
        print("密码修改成功！")
    else:
        print("两次输入的新密码不一致，修改失败。")

def show_available_books():
    print("\n可借阅的图书有:")
    for i in range(len(available_books)):
        print(f"{i+1}. {available_books[i]}")

def borrow_book(username):
    show_available_books()
    book_name = input("\n请输入要借阅的图书名称: ").strip()

    if book_name not in available_books:
        print("该图书不存在于可借阅列表中。")
        return

    # 检查该用户是否已经借了这本书且未归还
    user_records = borrow_records.get(username, [])
    for record in user_records:
        if record['book'] == book_name and not record['returned']:
            print(f"您尚未归还《{book_name}》，无法重复借阅。")
            return

    # 检查是否有其他人借了这本书且未归还
    for user, records in borrow_records.items():
        for record in records:
            if record['book'] == book_name and not record['returned']:
                print(f"《{book_name}》已被其他用户借阅且未归还，暂时无法借阅。")
                return

    # 借书
    if username not in borrow_records:
        borrow_records[username] = []
    
    # 添加借阅日期
    borrow_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    borrow_records[username].append({
        'book': book_name,
        'returned': False,
        'borrow_date': borrow_date
    })
    print(f"借阅成功！您已借阅《{book_name}》。")

def show_user_borrowed_books(username):
    user_records = borrow_records.get(username, [])
    borrowed = [r for r in user_records if not r['returned']]
    if not borrowed:
        print("您当前没有借阅任何图书。")
        return []

    print("\n您当前借阅的图书有:")
    for idx, record in enumerate(borrowed, 1):
        print(f"{idx}. 《{record['book']}》")
    return borrowed

def return_book(username):
    borrowed_books = show_user_borrowed_books(username)
    if not borrowed_books:
        return

    book_name = input("\n请输入要归还的图书名称: ").strip()
    user_records = borrow_records.get(username, [])
    found = False

    for record in user_records:
        if record['book'] == book_name and not record['returned']:
            record['returned'] = True
            print(f"归还成功！《{book_name}》已归还。")
            found = True
            break

    if not found:
        print("该图书不在您的借阅记录中，或已经归还。")

def query_records(username):
    user_records = borrow_records.get(username, [])
    if not user_records:
        print("您还没有任何借阅记录。")
        return

    print("\n您的借阅记录:")
    for record in user_records:
        status = "已归还" if record['returned'] else "未归还"
        borrow_date = record.get('borrow_date', '未知日期')
        print(f"《{record['book']}》 - 借阅日期: {borrow_date} - 状态: {status}")

def main():
    # 程序启动时加载数据
    load_data()
    
    current_user = None

    try:
        while True:
            if current_user is None:
                current_user = login()
                continue

            print("\n请选择操作:")
            print("1. 修改密码")
            print("2. 借书")
            print("3. 还书")
            print("4. 查询记录")
            print("5. 退出系统")

            try:
                choice = input("请输入选项 (1-5): ").strip()
            except:
                choice = ''

            if choice == '1':
                change_password(current_user)
            elif choice == '2':
                borrow_book(current_user)
            elif choice == '3':
                return_book(current_user)
            elif choice == '4':
                query_records(current_user)
            elif choice == '5':
                confirm = input("确认退出？(y/n): ").strip().lower()
                if confirm == 'y':
                    # 退出前保存数据
                    save_data()
                    print(f"感谢使用图书管理系统，再见，{current_user}！")
                    break
                else:
                    pass
            else:
                print("无效选项，请输入 1~5 之间的数字。")

            # 每次操作后暂停一下，避免刷屏（可选）
            input("\n按回车键继续...")
            
    except KeyboardInterrupt:
        # 处理Ctrl+C中断，确保数据保存
        print("\n\n程序被中断，正在保存数据...")
        save_data()
        print("数据已保存，再见！")
    except Exception as e:
        print(f"程序出现错误: {e}")
        # 出错时也尝试保存数据
        save_data()
    finally:
        # 确保在任何情况下都尝试保存数据
        if 'current_user' in locals() and current_user is not None:
            save_data()

if __name__ == "__main__":
    main()